package com.fanfanwang.ffw.app.ui.login;

import java.lang.reflect.Type;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import com.fanfanwang.ffw.app.AppConstant;
import com.fanfanwang.ffw.app.AppManager;
import com.fanfanwang.ffw.app.R;
import com.fanfanwang.ffw.app.asynctask.IsregReturnAsyncTask;
import com.fanfanwang.ffw.app.asynctask.SetNewPasswordAsyncTask;
import com.fanfanwang.ffw.app.bean.IsRegBean;
import com.fanfanwang.ffw.app.bean.SmsBean;
import com.fanfanwang.ffw.app.common.ToastAlone;
import com.fanfanwang.ffw.app.tools.SharedPreferencesUtil;
import com.fanfanwang.ffw.app.widget.CommonTitleBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/** 找回密码 */
public class FindPwdAct extends com.fanfanwang.ffw.app.base.BaseActivity {

	private CommonTitleBar commonTitleBar;
	private EditText re_et_mobile;
	private Button re_bt_getcode;
	private EditText re_et_code;
	private EditText re_et_password;
	private Button re_btn_complete;
	public String mobile = "";
	public String securityCode = "";
	public String password = "";
	private Activity mAct;
	private Intent mIntent;
	public StringBuffer smsString = new StringBuffer();// 这个是判断这个手机号是合法的，可以注册，然后返回的验证码
	public static IIsRegReturnable iIsRegReturnable;
	public static ISetNewPasswordable iSetNewPasswordable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppManager.getAppManager().addActivity(this);
		initWidget();
		initSMSsdk();
		initData();
		widgetClick();
	}

	public void initSMSsdk() {
		SMSSDK.initSDK(this, AppConstant.APPKEY, AppConstant.APPSECRET);
		EventHandler eh = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {

				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				handler.sendMessage(msg);
			}

		};
		SMSSDK.registerEventHandler(eh);
	}

	public void initWidget() {
		setContentView(R.layout.activity_find_pwd);
		mAct = this;
		commonTitleBar = (CommonTitleBar) findViewById(R.id.common_titlebar);
		re_bt_getcode = (Button) findViewById(R.id.re_bt_getcode);
		re_et_mobile = (EditText) findViewById(R.id.lo_mobile);
		re_et_code = (EditText) findViewById(R.id.lo_yzm);
		re_et_password = (EditText) findViewById(R.id.lo_password);
		re_btn_complete = (Button) findViewById(R.id.lo_btn_complete);
	}

	public void widgetClick() {
		commonTitleBar.setToolBarReturnOnclickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		re_bt_getcode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// new GetRegisterCodeAsyncTask().execute("");
				// new MyCount(60000, 1000).start();
				mobile = re_et_mobile.getText().toString();
				if (TextUtils.isEmpty(mobile)) {
					ToastAlone.showToast(mAct, getString(R.string.input));
				} else {
					new IsregReturnAsyncTask(mAct, mobile).execute("");
				}
			}
		});
		re_btn_complete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				securityCode = re_et_code.getText().toString();
				password = re_et_password.getText().toString();
				mobile = re_et_mobile.getText().toString();
				if (TextUtils.isEmpty(mobile)) {
					ToastAlone.showToast(FindPwdAct.this,
							getString(R.string.register_tel_no_null));
				} else if (TextUtils.isEmpty(securityCode)) {
					ToastAlone.showToast(FindPwdAct.this,
							getString(R.string.register_yzm_no_null));
				} else if (TextUtils.isEmpty(password)) {
					ToastAlone.showToast(FindPwdAct.this,
							getString(R.string.register_pwd_no_null));
				} else {
					// 验证一下验证码。如果成功就会回调
					SMSSDK.submitVerificationCode("86", mobile, securityCode);
					// 然后去回调哪里修改密码

				}
			}
		});
	}

	@Override
	public void initData() {
		commonTitleBar.setCenterText(getString(R.string.find_pwd));
		commonTitleBar.setReturnVisible();
		setInterface();
	}

	public class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);

		}

		@Override
		public void onFinish() {
			re_bt_getcode.setText(getString(R.string.register_reget));
			re_bt_getcode.setClickable(true);
			re_bt_getcode.setBackgroundResource(R.drawable.btn_selector);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			re_bt_getcode.setText("(" + millisUntilFinished / 1000 + ")");
			re_bt_getcode.setBackgroundResource(R.drawable.btn_back_3);// 灰色
			re_bt_getcode.setClickable(false);
		}

	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub

	}

	public interface IIsRegReturnable {// 验证码
		public void SetIsRegSms(IsRegBean data);

		public void setIsRegSmsFailed();
	}

	public interface ISetNewPasswordable {
		public void setNewPasswordSuccess();
	}

	public void setInterface() {
		iIsRegReturnable = new IIsRegReturnable() {

			@Override
			public void setIsRegSmsFailed() {
				// TODO Auto-generated method stub
//				new MyCount(60000, 1000).start();
			}

			@Override
			public void SetIsRegSms(IsRegBean data) {
				// TODO Auto-generated method stub
				// smsString.append(data.sms);
				// new MyCount(60000, 1000).start();
				// 发送验证码
				SMSSDK.getVerificationCode("86", mobile);
			}
		};
		iSetNewPasswordable = new ISetNewPasswordable() {

			@Override
			public void setNewPasswordSuccess() {
				// TODO Auto-generated method stub
				SharedPreferencesUtil.getInstance(mAct).putUserId(null);
				SharedPreferencesUtil.getInstance(mAct).putUsername(null);
				SharedPreferencesUtil.getInstance(mAct).putTruename(null);
				SharedPreferencesUtil.getInstance(mAct).putCarnumber(null);
				AppManager.getAppManager().finishAllActivity();
				AppConstant.user_id = "";
				AppConstant.username = "";
				Intent mIntent = new Intent(mAct, LoginAct.class);
				mIntent.putExtra("isNeedIntent", true);
				startActivity(mIntent);
				finish();
			}
		};

	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int event = msg.arg1;
			int result = msg.arg2;
			Object data = msg.obj;
			Log.e("event", "event=" + event);
			if (result == SMSSDK.RESULT_COMPLETE) {
				// 短信注册成功后，返回MainActivity,然后提示新好友
				if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
					// ToastAlone.makeText(getApplicationContext(), "提交验证码成功",
					// Toast.LENGTH_SHORT).show();
					// textView2.setText("提交验证码成功");
					new SetNewPasswordAsyncTask(mAct, mobile, password)
					.execute("");
				} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
					// 获取验证码成功(1步)
					Toast.makeText(getApplicationContext(), "验证码已经发送,60s后可以重新获取",
							Toast.LENGTH_SHORT).show();
					new MyCount(60000, 1000).start();
				} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {// 返回支持发送验证码的国家列表
//					Toast.makeText(getApplicationContext(), "获取国家列表成功",
//							Toast.LENGTH_SHORT).show();

				}
			} else {
				((Throwable) data).printStackTrace();
				if(data!=null)
				{
					String json=((Throwable)data).getMessage();
					
					Type type = new TypeToken<SmsBean>() {
					}.getType();
					SmsBean bean = new SmsBean();
					try {
						bean = new Gson().fromJson(json, type);
						if(!TextUtils.isEmpty(bean.status)&&bean.status.equals("520"))
						{
							ToastAlone.showToast(mAct, "验证码错误");
						}
					} catch (JsonSyntaxException e) {
						e.printStackTrace();
					}
				}
			}

		}

	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SMSSDK.unregisterAllEventHandler();
	}
}
